import protomessage_pb2 # 直接import会找不到module
import json

class C_deviceDataProcess:
    '''
    数据处理类
    '''
    def __init__(self):
        pass

    def device_init_data_get(self, data):
        aDict = self.device_data_get(data)
        try:
            device_ID = aDict["device_ID"]
            return device_ID , True
        except:
            print("数据处理错误")

    def device_data_get(self, data):
        '''
        解析数据
        '''
        aDict = json.loads(data)
        return aDict

    def device_data_set(self, data):
        '''
        构建数据
        '''
        pass
    def device_protobuf_get(self, aDict):
        '''
        作用：将特定的字典转化成特定的字符串 "Payload": {"USER_ID": 1381234432110, "Device_ID": 1, "Device_Type": 0, "Device_Num": 1, "DeviceSwitchState": 0, "Luminance": 1000, "Color": 50}
        输入：字典
        输出：二进制数据 protubuf 
        '''
        #print("class C_deviceDataProcess:device_protobuf_get:作用：将特定的字典转化成特定的字符串!", aDict)
        IlampProto = protomessage_pb2.ILampStateHeart()
        try:
            IlampProto.USER_ID     = aDict["USER_ID"]
            IlampProto.Device_ID   = aDict["Device_ID"]
            IlampProto.Device_Type = aDict["Device_Type"]
            IlampProto.Device_Num  = aDict["Device_Num"]
            IlampProto.DeviceSwitchState = aDict["DeviceSwitchState"]
            IlampProto.Luminance   = aDict["Luminance"]
            IlampProto.Color       = aDict["Color"]
        except:
            print("C_deviceDataProcess:device_protobuf_get:数据转换失败")
        protoData = IlampProto.SerializeToString()
        # print("class C_deviceDataProcess:device_protobuf_get:protodata:", protoData)
        return protoData
    
    def device_protobuf_set(self, protoData):
        '''
        作用：将特定的字典转化成特定的字符串 "Payload": {"USER_ID": 1381234432110, "Device_ID": 1, "Device_Type": 0, "Device_Num": 1, "DeviceSwitchState": 0, "Luminance": 1000, "Color": 50}
        输入：二进制数据 protubuf 
        输出：json 字符串
        '''
        IlampProto = protomessage_pb2.ILampStateHeart()
        try:
            IlampProto.ParseFromString(protoData)
        except:
            print("C_deviceDataProcess:device_protobuf_set:输入数据错误")
            return False
        try:
            aDict = {
                "USER_ID"           : IlampProto.USER_ID,
                "Device_ID"         : IlampProto.Device_ID,
                "Device_Type"       : IlampProto.Device_Type,
                "Device_Num"        : IlampProto.Device_Num,
                "DeviceSwitchState" : IlampProto.DeviceSwitchState,
                "Luminance"         : IlampProto.Luminance,
                "Color"             : IlampProto.Color,
                }
            return json.dumps(aDict)
        except:
            print("C_deviceDataProcess:device_protobuf_set:数据转换失败")
            return False
